package lotterysystem.lotterysystem.service.Impl;

import jakarta.annotation.Resource;
import lotterysystem.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import lotterysystem.lotterysystem.common.exception.ServiceException;
import lotterysystem.lotterysystem.common.utils.JacksonUtil;
import lotterysystem.lotterysystem.common.utils.RedisUtil;
import lotterysystem.lotterysystem.controller.param.CreateActivityParam;
import lotterysystem.lotterysystem.controller.param.CreatePrizeByActivityParam;
import lotterysystem.lotterysystem.controller.param.CreateUserByActivityParam;
import lotterysystem.lotterysystem.controller.param.PageParam;
import lotterysystem.lotterysystem.dao.dataobject.ActivityDO;
import lotterysystem.lotterysystem.dao.dataobject.ActivityPrizeDO;
import lotterysystem.lotterysystem.dao.dataobject.ActivityUserDO;
import lotterysystem.lotterysystem.dao.dataobject.PrizeDO;
import lotterysystem.lotterysystem.dao.mapper.*;
import lotterysystem.lotterysystem.service.ActivityService;
import lotterysystem.lotterysystem.service.dto.ActivityDTO;
import lotterysystem.lotterysystem.service.dto.ActivityDetailDTO;
import lotterysystem.lotterysystem.service.dto.CreateActivityDTO;
import lotterysystem.lotterysystem.service.dto.PageListDTO;
import lotterysystem.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import lotterysystem.lotterysystem.service.enums.ActivityPrizeTiersEnum;
import lotterysystem.lotterysystem.service.enums.ActivityStatusEnum;
import lotterysystem.lotterysystem.service.enums.ActivityUserStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl implements ActivityService {

    private static final Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class);

    // 活动缓存前缀
    private final String ACTIVITY_PREFIX = "ACTIVITY_";

    // 活动缓存过期时间
    private final Long ACTIVITY_TIMEOUT = 60 * 60 * 24 * 3L;
    @Resource
    private UserMapper userMapper;

    @Resource
    private PrizeMapper prizeMapper;

    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private ActivityUserMapper activityUserMapper;

    @Resource
    private ActivityPrizeMapper activityPrizeMapper;

    @Resource
    private RedisUtil redisUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CreateActivityDTO createActivity(CreateActivityParam param) {
        // 校验活动信息是否正确
        checkActivityInfo(param);
        // 保存活动信息
        ActivityDO activityDO = new ActivityDO();
        activityDO.setActivityName(param.getActivityName());
        activityDO.setDescription(param.getDescription());
        activityDO.setStatus(ActivityStatusEnum.RUNNING.name());
        activityMapper.insert(activityDO);
        // 保存相关联的奖品信息
        List<CreatePrizeByActivityParam> prizeParams = param.getActivityPrizeList();
        List<ActivityPrizeDO> activityPrizeDOList = prizeParams.stream()
                .map(prizeParam -> {
                    ActivityPrizeDO activityPrizeDO = new ActivityPrizeDO();
                    activityPrizeDO.setActivityId(activityDO.getId());
                    activityPrizeDO.setPrizeId(prizeParam.getPrizeId());
                    activityPrizeDO.setPrizeAmount(prizeParam.getPrizeAmount());
                    activityPrizeDO.setPrizeTiers(prizeParam.getPrizeTiers());
                    activityPrizeDO.setStatus(ActivityPrizeStatusEnum.INIT.name());
                    return activityPrizeDO;
                }).collect(Collectors.toList());
        activityPrizeMapper.batchInsert(activityPrizeDOList);
        // 保存相关的人员信息
        List<CreateUserByActivityParam> userParams = param.getActivityUserList();
        List<ActivityUserDO> activityUserDOList = userParams.stream()
                .map(userParam -> {
                    ActivityUserDO activityUserDO = new ActivityUserDO();
                    activityUserDO.setActivityId(activityDO.getId());
                    activityUserDO.setUserId(userParam.getUserId());
                    activityUserDO.setUserName(userParam.getUserName());
                    activityUserDO.setStatus(ActivityUserStatusEnum.INIT.name());
                    return activityUserDO;
                }).collect(Collectors.toList());
        activityUserMapper.batchInsert(activityUserDOList);
        // 整合完整的活动信息，存redis
        // 先获取奖品的基本属性列表
        // 获取需要查询的奖品id
        List<Long> prizeIds = param.getActivityPrizeList().stream()
                .map(CreatePrizeByActivityParam::getPrizeId)
                .distinct()
                .collect(Collectors.toList());
        List<PrizeDO> prizeDOList = prizeMapper.batchSelectByIds(prizeIds);
        ActivityDetailDTO activityDetailDTO = convertToActivityDetailDTO(activityDO,activityUserDOList,
                prizeDOList,activityPrizeDOList);
        cacheActivity(activityDetailDTO);
        // 构造返回
        CreateActivityDTO createActivityDTO = new CreateActivityDTO();
        createActivityDTO.setActivityId(activityDO.getId());
        return createActivityDTO;
    }

    @Override
    public PageListDTO<ActivityDTO> findActivityList(PageParam param) {
        // 获取总量
        int total = activityMapper.count();

        // 获取当前列表
        List<ActivityDO> activityDOList = activityMapper.selectActivityList(param.offset(),param.getPageSize());
        List<ActivityDTO> activityDTOList = activityDOList.stream()
                .map(activityDO -> {
                    ActivityDTO activityDTO = new ActivityDTO();
                    activityDTO.setActivityId(activityDO.getId());
                    activityDTO.setActivityName(activityDO.getActivityName());
                    activityDTO.setDescription(activityDO.getDescription());
                    activityDTO.setStatus(ActivityStatusEnum.forName(activityDO.getStatus()));
                    return activityDTO;
                }).collect(Collectors.toList());
        return new PageListDTO<>(total,activityDTOList);
    }


    @Override
    public ActivityDetailDTO getActivityDetail(Long activityId) {
        //非空校验
        if (null == activityId) {
            logger.warn("查询活动信息失败，activityId为空！");
            return null;
        }
        // 查询redis
        ActivityDetailDTO detailDTO = getActivityFromCache(activityId);
        if (null != detailDTO) {
            logger.info("查询活动信息成功！detailDTO:{}",
                    JacksonUtil.writeValueAsString(detailDTO));
        }


        // redis中不存在，查表
        //活动表
        ActivityDO aDO = activityMapper.selectById(activityId);

        //活动奖品表
        List<ActivityPrizeDO> apDOList = activityPrizeMapper.selectByActivityId(activityId);

        //活动人员表
        List<ActivityUserDO> auDOList = activityUserMapper.selectByActivityId(activityId);

        //奖品表,先获取要查询的奖品id
        List<Long> prizeIds = apDOList.stream().
                map(ActivityPrizeDO::getPrizeId).
                collect(Collectors.toList());
        List<PrizeDO> pDOList = prizeMapper.batchSelectByIds(prizeIds);
        //整合信息，存redis
        detailDTO = convertToActivityDetailDTO(aDO,auDOList,pDOList,apDOList);
        cacheActivity(convertToActivityDetailDTO(aDO,auDOList,pDOList,apDOList));
        //返回
        return detailDTO;
    }

    @Override
    public void cacheActivity(Long activityId) {
        if (null == activityId) {
            logger.warn("要缓存的活动id为空！");
            throw new ServiceException(ServiceErrorCodeConstants.CACHE_ACTIVITY_ID_IS_EMPTY);
        }
        //查询表数据：活动表，关联奖品，关联人员，奖品信息
        ActivityDO aDO = activityMapper.selectById(activityId);
        if (null == aDO) {
            logger.warn("要缓存的活动id有误！");
            throw new ServiceException(ServiceErrorCodeConstants.CACHE_ACTIVITY_ID_ERROR);
        }
        //活动奖品表
        List<ActivityPrizeDO> apDOList = activityPrizeMapper.selectByActivityId(activityId);
        //活动人员表
        List<ActivityUserDO> auDOList = activityUserMapper.selectByActivityId(activityId);

        //奖品表,先获取要查询的奖品id
        List<Long> prizeIds = apDOList.stream().
                map(ActivityPrizeDO::getPrizeId).
                collect(Collectors.toList());
        List<PrizeDO> pDOList = prizeMapper.batchSelectByIds(prizeIds);
        //整合信息，存redis
        cacheActivity(convertToActivityDetailDTO(aDO,auDOList,pDOList,apDOList));

    }

    /**
     * 缓存完整的活动信息
     * @param detailDTO
     */
    private void cacheActivity(ActivityDetailDTO detailDTO) {
        // key ： ACTIVITY_activityId
        // value ： ActivityDetailDTO(json)
        if (null == detailDTO || null == detailDTO.getActivityId()) {
            logger.warn("要缓存的活动信息不存在！");
            return;
        }
        try {
            redisUtil.set(ACTIVITY_PREFIX + detailDTO.getActivityId(),
                    JacksonUtil.writeValueAsString(detailDTO),
                    ACTIVITY_TIMEOUT);
        } catch (Exception e) {
            logger.error("缓存活动异常，ActivityDetailDTO：{}",
                    JacksonUtil.writeValueAsString(detailDTO),
                    e);
        }
    }

    /**
     * 根据活动id从缓存中获取活动信息
     * @param activityId 活动id
     * @return 活动信息
     */
    private ActivityDetailDTO getActivityFromCache(Long activityId) {
        if (null == activityId) {
            logger.warn("获取缓存活动信息的activityId为空！");
            return null;
        }
        try {
            String s = redisUtil.get(ACTIVITY_PREFIX + activityId);
            //非空校验
            if (!StringUtils.hasText(s)) {
                logger.info("获取缓存数据为空！key：{}",ACTIVITY_PREFIX + activityId);
            }
            return JacksonUtil.readValue(s, ActivityDetailDTO.class);

        } catch (Exception e) {
            logger.error("从缓存中获取活动信息异常，key：{}",ACTIVITY_PREFIX + activityId,e);
            return null;
        }
    }

    private ActivityDetailDTO convertToActivityDetailDTO(ActivityDO activityDO,
                                            List<ActivityUserDO> activityUserDOList,
                                            List<PrizeDO> prizeDOList,
                                            List<ActivityPrizeDO> activityPrizeDOList) {

        ActivityDetailDTO detailDTO = new ActivityDetailDTO();
        detailDTO.setActivityId(activityDO.getId());
        detailDTO.setActivityName(activityDO.getActivityName());
        detailDTO.setDescription(activityDO.getDescription());
        detailDTO.setStatus(ActivityStatusEnum.forName(activityDO.getStatus()));

        List<ActivityDetailDTO.PrizeDTO> prizeDTOList = activityPrizeDOList.stream()
                        .map(apDO -> {
                            ActivityDetailDTO.PrizeDTO prizeDTO = new ActivityDetailDTO.PrizeDTO();
                            prizeDTO.setPrizeId(apDO.getPrizeId());
                            Optional<PrizeDO> optionalPrizeDO = prizeDOList.stream().filter(prizeDO -> prizeDO.getId().equals(apDO.getPrizeId()))
                                    .findFirst();
                            // 如果PrizeDO为空，不执行当前方法，不为空才执行
                            optionalPrizeDO.ifPresent(prizeDO -> {
                                prizeDTO.setName(prizeDO.getName());
                                prizeDTO.setImageUrl(prizeDO.getImageUrl());
                                prizeDTO.setPrice(prizeDO.getPrice());
                                prizeDTO.setDescription(prizeDO.getDescription());
                            });
                            prizeDTO.setTiers(ActivityPrizeTiersEnum.forName(apDO.getPrizeTiers()));
                            prizeDTO.setPrizeAmount(apDO.getPrizeAmount());
                            prizeDTO.setStatus(ActivityPrizeStatusEnum.forName(apDO.getStatus()));
                            return prizeDTO;
                        }).collect(Collectors.toList());
        logger.info("prizeDTOList content:{}",JacksonUtil.writeValueAsString(prizeDTOList));
        detailDTO.setPrizeDTOList(prizeDTOList);
        List<ActivityDetailDTO.UserDTO> userDTOList = activityUserDOList.stream()
                        .map(auDO -> {
                            ActivityDetailDTO.UserDTO userDTO = new ActivityDetailDTO.UserDTO();
                            userDTO.setUserId(auDO.getUserId());
                            userDTO.setUserName(auDO.getUserName());
                            userDTO.setStatus(ActivityUserStatusEnum.forName(auDO.getStatus()));
                            return userDTO;
                        }).collect(Collectors.toList());
        detailDTO.setUserDTOList(userDTOList);
        return detailDTO;

    }

    /**
     * 校验活动的有效性
     * @param param
     */
    private void checkActivityInfo(CreateActivityParam param) {
        if (null == param) {
            throw new ServiceException(ServiceErrorCodeConstants.CREATE_ACTIVITY_INFO_IS_EMPTY);
        }
        // 人员id在人员表中是否存在
        List<Long> userIds = param.getActivityUserList()
                .stream()
                .map(CreateUserByActivityParam::getUserId)
                .distinct()
                .collect(Collectors.toList());

        List<Long> exitsUserIds = userMapper.selectExistByIds(userIds);
        if (CollectionUtils.isEmpty(exitsUserIds)) {
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_USER_ERROR);
        }
        userIds.forEach(id -> {
            if (!exitsUserIds.contains(id)) {
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_USER_ERROR);
            }
        });
        // 奖品id是否存在
        List<Long> prizeIds = param.getActivityPrizeList()
                .stream()
                .map(CreatePrizeByActivityParam::getPrizeId)
                .distinct()
                .collect(Collectors.toList());
        List<Long> exitsPrizeIds = prizeMapper.selectExistByIds(prizeIds);
        if (CollectionUtils.isEmpty(exitsPrizeIds)) {
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_ERROR);
        }
        prizeIds.forEach(id -> {
            if (!exitsPrizeIds.contains(id)) {
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_ERROR);
            }
        });
        // 人员数量大于等于奖品数量
        int userAmount = param.getActivityUserList().size();
        long prizeAmount = param.getActivityPrizeList()
                .stream()
                .mapToLong(CreatePrizeByActivityParam::getPrizeAmount)
                .sum();

        if (userAmount < prizeAmount) {
            throw new ServiceException(ServiceErrorCodeConstants.USER_PRIZE_AMOUNT_ERROR);
        }

        param.getActivityPrizeList().forEach(prize -> {
            if (null == ActivityPrizeTiersEnum.forName(prize.getPrizeTiers())) {
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_TIERS_ERROR);
            }
        });
    }
}
